package com.example.common.mvvm.view;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.viewbinding.ViewBinding;

import com.example.common.mvvm.databus.LiveDataEntity;
import com.example.common.mvvm.viewmodel.BaseViewModel;

import org.jetbrains.annotations.NotNull;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;

public abstract class BaseFragment<V extends ViewBinding,VM extends BaseViewModel> extends Fragment implements IView {

    protected LayoutInflater inflater;
    protected V v;
    protected VM vm;
    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflater = LayoutInflater.from(getContext());
        v = (V) initBinding();
        initViewModel();
        getLifecycle().addObserver(vm);

    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        initView();
        initData();
        return bindLayout();
    }

    @Override
    public void initViewModel() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        Class clazz = (Class) type.getActualTypeArguments()[1];
        vm = (VM) new ViewModelProvider(this,new ViewModelProvider.NewInstanceFactory())
                .get(clazz);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        getLifecycle().removeObserver(vm);
    }

    public static class LiveDataFragment implements Observer<LiveDataEntity> {

        private WeakReference<BaseFragment> weakReference;

        public LiveDataFragment(BaseFragment baseFragment) {
            weakReference=new WeakReference<>(baseFragment);
        }

        @Override
        public void onChanged(LiveDataEntity liveDataEntity) {
            if (weakReference.get()==null||liveDataEntity==null|| liveDataEntity.action==null){
                return;
            }
        }
    }

}
